<template>
  <div>
      <div class="my-upload">
          <h3>+</h3>
          <img v-if="imgUrl" :src="imgUrl" alt=""/>
          <input type="file" @change="getFile"/>
      </div>
  </div>
</template>
<script>
import { mapGetters, mapActions } from "vuex";
import path from 'path';
import {errorAlert} from '../utils/alert'

export default {
  props: [],
  data() {
    return {
        imgUrl:'',
    };
  },
  computed: {
    ...mapGetters({}),
  },
  mounted() {},
  methods: {
    ...mapActions({}),
    getFile(e){
        let file = e.target.files[0];
        //验证文件大小
        if(file.size>2*1024*1024){
            errorAlert('文件最大2M');
            return;
        }
        //验证文件类型
        let extname = path.extname(file.name);
        let imgArr = ['.png','.jpg','.jpeg','.gif','.webp']
        if(!imgArr.includes(extname)){
            errorAlert('请上传正确的图片格式');
            return;
        }
        //生成一张图
        this.imgUrl = URL.createObjectURL(file);
        //赋值给user.img  子传父，将文件传给父组件
        this.$emit('sendFile',file)
    },
    setImgUrl(url){
        this.imgUrl = url;
    }
  },
};
</script>
<style scoped lang="less">
@import "../less/index.less";
.my-upload{
    width: 100px;
    height: 100px;
    border: 1px dashed @primary-light;
    position: relative;
    h3{
        text-align: center;
        line-height: 100px;
    }
    input,img{
        position: absolute;
        left: 0;
        top: 0;
        width: 100%;
        height: 100%;
        cursor: pointer;
    }
    input{
        opacity: 0;
    }
}
</style>